#include <signal.h>

#include <iostream>
using std::cout;
using std::endl;
using std::string;

#include <workflow/WFFacilities.h>
#include <workflow/WFTaskFactory.h>
#include <workflow/MySQLMessage.h>
#include <workflow/MySQLResult.h>


//通过构造函数初始化计数器的值 
static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int num)
{
    printf("sig %d is coming\n", num);
    //将计数器的值减1
    waitGroup.done();
}

void mysqlCallback(WFMySQLTask * mysqltask)
{
    printf("mysqlCallback is running.\n");
    //0. 对任务的状态进行检测
    int state = mysqltask->get_state();
    int error = mysqltask->get_error();
    if(state != WFT_STATE_SUCCESS) {
        printf("%s\n", WFGlobal::get_error_string(state, error));
        return;
    }
    //1. 检测SQL语句是否存在语法错误
    auto resp = mysqltask->get_resp();
    if(resp->get_packet_type() == MYSQL_PACKET_ERROR) {
        printf("ERROR %d: %s\n", resp->get_error_code(),
               resp->get_error_msg().c_str());
        return;
    }
    printf("sql sentence is ok.\n");
    //2. 写操作
    protocol::MySQLResultCursor cursor(resp);
    if(cursor.get_cursor_status() == MYSQL_STATUS_OK) {
        printf("Query OK. %llu row affected.\n",cursor.get_affected_rows());
    }

}


void test0()
{
    signal(SIGINT, sighandler);

    //1. 创建MySQL任务
    string url("mysql://root:1234@localhost");
    auto mysqlTask = WFTaskFactory::create_mysql_task(url, 1, mysqlCallback);
    string sql("INSERT INTO cloudisk.tbl_user_token(user_name, user_token) VALUES('Guanyu', 'Guanyuaaaaa')");
    //2. 设置任务的属性
    mysqlTask->get_req()->set_query(sql);
    //3. 将任务交给框架来调度执行
    mysqlTask->start();

    waitGroup.wait();
}


int main()
{
    test0();
    printf("exit main\n");
    return 0;
}

